package com.pj.wisdomlogistics.ui.view.recyclerview;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by wufan on 2017/5/4.
 */

public abstract class GridRecyclerOnScrollListener extends
        RecyclerView.OnScrollListener {

    int lastVisibleItem;

    private int currentPage = 1;
    private boolean loading = false;

    private GridLayoutManager mGridLayoutManager;

    private boolean isUp;

    public GridRecyclerOnScrollListener(
            GridLayoutManager mGridLayoutManager) {
        this.mGridLayoutManager = mGridLayoutManager;
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        lastVisibleItem = mGridLayoutManager.findLastVisibleItemPosition();
    }

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);

        if (mTouchListener == null) {
            mTouchListener = new View.OnTouchListener() {
                private float preY = 0;
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if(event.getAction() == MotionEvent.ACTION_MOVE){
                        float y = event.getY();
                        if(y > preY){
                            isUp = false;
                        }else if(y < preY){
                            isUp = true;
                        }
                        preY = y;
                    }
                    return false;
                }
            };
            recyclerView.setOnTouchListener(mTouchListener);
        }



        //0：当前屏幕停止滚动；1时：屏幕在滚动 且 用户仍在触碰或手指还在屏幕上；2时：随用户的操作，屏幕上产生的惯性滑动；
        // 滑动状态停止并且剩余少于两个item时，自动加载下一页
        if (!loading && newState == RecyclerView.SCROLL_STATE_IDLE && isUp
                && lastVisibleItem +2>=mGridLayoutManager.getItemCount()) {
            currentPage++;
            loading = true;
            onLoadMore(currentPage);
        }
    }

    public abstract void onLoadMore(int currentPage);

    public void setLoading(boolean loading){
        this.loading = loading;
        if(!isUp){
            currentPage = 1;
        }
    }

    View.OnTouchListener mTouchListener = null;
}
